package com.wngbms.websocket.user;

import com.alibaba.fastjson.JSON;
import com.wngbms.websocket.entity.UserMetaInfo;
import com.wngbms.websocket.zookeeper.ZkConst;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class RedisUserMetaInfoHandler implements UserMetaInfoHandler, ZkConst {

    @Autowired
    RedissonClient redissonClient;

    @Override
    public void setUserMetaInfo(UserMetaInfo userMetaInfo) {
        RBucket<String> bucket = redissonClient.getBucket(getUserKey(userMetaInfo.getUserId()));
        String userInfo = JSON.toJSONString(userMetaInfo);
        bucket.set(userInfo);
    }

    @Override
    public UserMetaInfo getUserMetaInfo(String userId) {
        RBucket<String> bucket = redissonClient.getBucket(getUserKey(userId));
        String userInfo = bucket.get();
        if (StringUtils.isNotBlank(userInfo)) {
            return JSON.parseObject(userInfo, UserMetaInfo.class);
        }
        return null;
    }

    @Override
    public void deleteUserMetaInfo(String userId) {
        RBucket<String> bucket = redissonClient.getBucket(getUserKey(userId));
        bucket.delete();
    }

}
